package com.ruoyi.web.controller.category;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.lang.WeightRandom;
import cn.hutool.core.util.RandomUtil;
import com.ruoyi.common.constant.SysConstants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.task.domain.SysFault;
import com.ruoyi.task.service.ISysFaultService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.category.service.ISysSubjectService;

/**
 * 科目信息
 * 
 * @author yjf
 */
@RestController
@RequestMapping("/category/subject")
public class SysSubjectController extends BaseController
{
    @Autowired
    private ISysSubjectService subjectService;

    @Autowired
    private ISysFaultService sysFaultService;

    @Autowired
    private ISysDeptService deptService;

    /**
     * 获取单位列表
     */
    @PreAuthorize("@ss.hasPermi('category:subject:list')")
    @GetMapping("/list")
    public AjaxResult list(SysDept subject)
    {
        List<SysDept> subjects = subjectService.selectSubjectList(subject);
        return AjaxResult.success(subjects);
    }

    /**
     * 根据编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('category:subject:query')")
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId)
    {
        deptService.checkDeptDataScope(deptId);
        return AjaxResult.success(deptService.selectDeptById(deptId));
    }

    /**
     * 根据parentId，故障随机类型获取故障现象列表
     *
     */
    @PreAuthorize("@ss.hasPermi('category:subject:query')")
    @PostMapping("/faultList")
    public AjaxResult faultList(@RequestBody SysFault sysFault) {
        //新增
        if (StringUtils.isNull(sysFault.getTaskNo()) || sysFault.getTaskNo() == 0) {
            if (StringUtils.isNull(sysFault.getParentId()) || sysFault.getParentId() == 0) {
                return AjaxResult.error("请先选择设备故障！");
            }
            SysDept subject = new SysDept();
            subject.setType(SysConstants.CONSTANT_STR6); //故障现象
            subject.setParentId(sysFault.getParentId());
            List<SysDept> subjectList = subjectService.selectSubjectList(subject);

            Long deptId = 0L;
            //如果是随机:faultType="1",根据权重进行随机算法组装数据返回结果
            if ("1".equals(sysFault.getFaultType())) {
                List<WeightRandom.WeightObj<Long>> weightList = new ArrayList<>();
                for (SysDept sub : subjectList) {
                    weightList.add(new WeightRandom.WeightObj<>(sub.getDeptId(), Integer.parseInt(sub.getFigure())));
                }
                WeightRandom weRandom = RandomUtil.weightRandom(weightList);
                deptId = Long.valueOf(weRandom.next().toString());
            }
            //组装数据
            List<SysFault> faultList = new ArrayList<>();
            for (SysDept sub : subjectList) {
                int status = 2;   //用于显示此次随机的是哪一项
                if (deptId != 0L && deptId.equals(sub.getDeptId())) {
                    status = 1;
                }
                SysFault fault = new SysFault();
                fault.setDeptId(sub.getDeptId());
                fault.setChildName(sub.getDeptName());
                fault.setWeight(Integer.parseInt(sub.getFigure()));
                fault.setStatus(status);
                faultList.add(fault);
            }
            return AjaxResult.success(faultList);
        } else {
            //查询记录表内容
            List<SysFault> fault = sysFaultService.selectSysFaultList(sysFault);
            return AjaxResult.success(fault);
        }
    }

    /**
     * 获取单位下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysDept subject)
    {
        List<SysDept> subjects = subjectService.selectSubjectList(subject);
        return AjaxResult.success(subjectService.buildSubjectTreeSelect(subjects));
    }

    /**
     * 新增类别
     */
    @PreAuthorize("@ss.hasPermi('category:subject:add')")
    @Log(title = "新增类别", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept)
    {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return AjaxResult.error("新增单位'" + dept.getDeptName() + "'失败，单位名称已存在");
        }
        dept.setCreateBy(getUsername());
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改类别
     */
    @PreAuthorize("@ss.hasPermi('category:subject:edit')")
    @Log(title = "修改类别", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDept dept)
{
    Long deptId = dept.getDeptId();
    deptService.checkDeptDataScope(deptId);
    if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
    {
        return AjaxResult.error("修改单位'" + dept.getDeptName() + "'失败，单位名称已存在");
    }
    else if (dept.getParentId().equals(deptId))
    {
        return AjaxResult.error("修改单位'" + dept.getDeptName() + "'失败，上级单位不能是自己");
    }
    else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId).size() > 0)
    {
        return AjaxResult.error("该单位包含未停用的子单位！");
    }
    dept.setUpdateBy(getUsername());
    return toAjax(deptService.updateDept(dept));
}

    /**
     * 删除类别
     */
    @PreAuthorize("@ss.hasPermi('category:subject:remove')")
    @Log(title = "类别管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable("deptId") Long deptId)
    {
        if (deptService.hasChildByDeptId(deptId))
        {
            return AjaxResult.error("存在下级单位,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId))
        {
            return AjaxResult.error("单位存在用户,不允许删除");
        }
        deptService.checkDeptDataScope(deptId);
        return toAjax(deptService.deleteDeptById(deptId));
    }
}